
L.TextTool = L.Tool.extend({

  enable: function(editor){
    L.Tool.prototype.enable.call(this, editor);
    this.name = "text_tool";
    // Drawing state
    this._drawing = false;
    this._c = null;
    this._x = 0;
    this._y = 0;
    this._w = 0;
    this._h = 0;
    this._px = 0;
    this._py = 0;
    this._selectElementId = null;
    this._textAreaEnable = true;
  },

  onDragstartElement: function(element, event){},
  onDragmoveElement: function(element, event){},
  onDragendElement: function(element, event){},

  onDragstartCanvas: function(canvas, event){
    if(this._textAreaEnable == false){
      document.activeElement.blur();
      this._textAreaEnable = true;
      return;
    }
    document.activeElement.blur();
    this._drawing = true;
    var pos = canvas.getPos(event);

    this._c = canvas.getRaphael().rect();
    this._x = pos.x;
    this._y = pos.y;
    this._px = event.pageX;
    this._py = event.pageY;

    this._c.attr({ 
      stroke: '#aaa',
      "stroke-opacity": this._options.opacity(),
      "stroke-width": 1, //*canvas.scale(),
      "x":this._x,
      "y":this._y,
      "width":2,
      "height":2,
      "fill": "#ffffff"
    });
    this._glow = this._c.glow({color: '#ccc'});
  },

  onDragmoveCanvas: function(canvas, event){
    if (this._drawing == true) {
      var pos = canvas.getPos(event);
      var x = this._x;
      var y = this._y;
      var dx = (pos.x-x);
      var dy = (pos.y-y);
      if(dx<0){
        x=pos.x;
        dx=-dx;
        this._px = event.pageX;
      }
      if(dy<0){
        y=pos.y;
        dy=-dy;
        this._py = event.pageY;
      }
      this._c.attr({x:x, y:y, width:dx, height:dy});

      this._glow.remove();
      this._glow = this._c.glow({color: '#ccc'});
    }
  },

  onDragendCanvas: function(canvas, event){
    if (this._drawing == true) {
      this._drawing = false;
      var self = this;
      var box = this._c.getBBox();
      if(box.width <10 && box.height<10){
        var elem = this._findIntersectedText(canvas,box);
        if(elem!=null){
          this._showInput(canvas, elem.getBBox(), elem);
          this._selectElementId = elem.id;
          this._c.remove(); 
          this._glow.remove();
          return; 
        }
      }

      var path = null;
      if (this._c != null) {
        path = this._c;
        // fix stroke width; the visible width is
        // scaled along the editor, but viewers 
        // should render the intended width
        var box = path.attr(['x','y','width','height'])
        this._showInput(canvas, box)
        path.remove();
        this._glow.remove(); 
      }
      this._c = null;
    }
  },

  disable: function(editor){
    document.activeElement.blur();
  },

  _findIntersectedText: function(canvas, box){
    var self = this;
    var elem = null;
    canvas.eachElement(function(el){
      if(el._attrs.type == "text" && elem == null){
        var inter = el.intersectWithBox(box);
        if(inter){
          elem = el._element;
        }
      }
    });
    return elem;
  },

  _drawRect: function(canvas, elem, show){
    if(show){
      var b = elem.getBBox();
      this._boxSelection = canvas.getRaphael().rect();
      this._boxSelection.attr({ 
        stroke: '#aaa',
        "stroke-opacity": this._options.opacity(),
        "stroke-width": 1, //*canvas.scale(),
        "x":b.x,
        "y":b.y,
        "width":b.width,
        "height":b.height,
        //"fill": "#ffffff"
      });
      this._boxSelectionGlow = this._boxSelection.glow({color: 'rgb(115, 135, 240)'});
    }else{
      this._boxSelection.remove(); 
      this._boxSelectionGlow.remove(); 
    }
  },
  
  getSelectedElementId: function(){
    return this._selectElementId;
  },

  _showInput: function(canvas, box, elem){
    console.log('elem');console.log(elem);
    var self = this;
    text_old = "";
    box = box || { width: 134, height: 70 };
    var x = this._px;
    var y = this._py;
    var width = box.width;
    var height = box.height-10;
    var color = self._options.color();
    if(elem){
      console.log("elem");console.log(elem);
      x = $(elem[0]).offset().left;
      y = $(elem[0]).offset().top;
      text_old = elem.attrs['text'];
      color = elem.attrs['fill'];
      self._drawRect(canvas, elem, true);

      var aux_elem = self._canvas.getRaphael().text(0, 0, text_old);
      var first = aux_elem.getBBox().width;
      aux_elem.attr({
        'font-size':24,
        'text-anchor': 'start',
      });
      width = aux_elem.getBBox().width;
      aux_elem.remove();
      //console.log("first:" + first + " last: " + width);

    }

    width = width > 120 ? width : 120 ;
    height = height > 60 ? height : 60 ;

    var input = $("<textarea id='inputElement'>"+ text_old.replace(/\n/g, ' ') +"</textarea>");
    $(document.body).append(input);
    self._textAreaEnable = false;
    input
      .css({
        'position':'absolute',
        'width':width, 'height':height,
        'top':y, 'left':x,
        'font-size': '18pt',
        'color': color,
        'background': 'rgba(255,255,255,0.8)'
      })
      .resizable({ minHeight: 30, minWidth: 60 })
      .focus()
      .blur(function(){
        var text = $(this).val();
        if(text.length > 0){
          if(!elem){
            //es creacion
            height = $(this).height();
            width = $(this).width();
            x = $(this).offset().left;
            y = $(this).offset().top;
            el =  self._canvas.getRaphael().text(box.x+10, box.y+10, text);
            el.attr({
              'font-size':24,
              'text-anchor': 'start',
              'fill': color,
            });
            var fitted_text = self._fitText(text, width);
            el.attr({ 'text': fitted_text });
            var attrs = el.attr();
            attrs.type = 'text';
            attrs.logical_type = "text";
            attrs.box_width = width;
            attrs.box_height = height;
  
            //console.log("attrs: type"+attrs.type);
            //console.log(attrs);
            var textElement = new L.Element(attrs);
            self._canvas.addElement(textElement);
            console.log("textElement");
            console.log(textElement);
            el.remove();

          }else{
            //es actualizacion
            height = $(this).height();
            width = $(this).width();
            var fitted_text = self._fitText(text, width);
            console.log("fitted_text="+fitted_text);
            console.log("fi_old_text="+text_old);
            if(fitted_text != text_old){
              elem.attr({ 'text': fitted_text });
              var attrs = elem.attr(['text']);
              attrs['id']= elem.id;
              if(attrs.id && typeof attrs.id == "string"){
                self._canvas.updateElement(attrs.id, attrs);
                console.log("updated");
              }
            }
            self._drawRect(canvas, elem, false);
          }
        }
        $(this).remove();
      })    
  },

  _fitText: function(text, max_width) {
        var aux_elem = this._canvas.getRaphael().text(200, 200, "");

        aux_elem.attr({
          'font-size':24,
          'text-anchor': 'start',
        });

        var result_text = "";

        var words = text.split(/[\s-]/);
        if(words.length>0){
          var line = words[0];
          for (i=1,n=words.length;i<n;i++) {
            var word = words[i];
  
            aux_elem.attr({ 'text': line + " " + word });
            if(aux_elem.getBBox().width <= max_width){
                line +=  " " + word;
            }else{
                result_text += line + "\n";
                line = word;
            }
          }
          result_text += line;
        }
        aux_elem.remove();
        return result_text
  },

  _fitText_old: function(elem, text, color,  max_width) {
        elem.attr({
          'font-size':24,
          'text-anchor': 'start',
          'fill': color,
        });

        

        var original_attr = elem.attr(['text','transform']);
        //var original_text = attr.text;
        var width_old = elem.getBBox().width;
        elem.transform("");
        var width = elem.getBBox().width;
        console.log("width: " +width_old + " - " + width);
        max_width = width;

        console.log('_ajustText - elem');console.log(elem);
        console.log('_ajustText - maxWidht');console.log(max_width);

        var result_text = "";

        var words = text.split(/[\s-]/);
        if(words.length>0){
          var line = words[0];
          for (i=1,n=words.length;i<n;i++) {
            var word = words[i];
  
            elem.attr({ 'text': line + " " + word });
            if(elem.getBBox().width <= max_width){
                line +=  " " + word;
            }else{
                result_text += line + "\n";
                line = word;
            }
          }
          result_text += line;
        }
        //elem.attr({ 'text': original_text });
        //elem.attr(original_attr);
        return result_text
  }
});